﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{
    [Navigation("干线流程", "开票管理")]
    [Function("eLogistics.RevenueMachineAccountManagement")]
    [PageTabber(Index = 0, NavigateUrl = "~/Finance/RevenueMachineAccountManagement.aspx", Title = "营收台帐管理", Type = typeof(RevenueMachineAccountManagement))]
    [PageTabber(Index = 1, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-StatementOfAccount.aspx", Title = "对帐管理", Type = typeof(RevenueMachineAccountManagement_StatementOfAccount))]
    [PageTabber(Index = 2, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-Invoice.aspx", Title = "开票管理", Type = typeof(RevenueMachineAccountManagement_Invoice))]
    [PageTabber(Index = 3, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-AccountsReceivable.aspx", Title = "收款管理", Type = typeof(RevenueMachineAccountManagement_AccountsReceivable))]

    public partial class RevenueMachineAccountManagement_Invoice : NavigationPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btnBatchConfirm.Attributes.Add("onclick", "chooseOrderForInvoice('{0}');return false;".Formato(this.gridOrderList.ClientID));
            if (!IsPostBack)
            {
                PageQueryAdapter1.PageSize = 20;


                txtConfirmInvoiceDateStart.Text =
 DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");

                txtConfirmInvoiceDateEnd.Text =
   DateTime.Now.ToString("yyyy-MM-dd");

   this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);
   ddlCompany.InsertEmptyItem(ListEmptyType.Select);
   if (!this.IsSuperRoles())
   {
       ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
       ddlCompany.Enabled = false;
   }
                PageQueryAdapter1.PerformQuery();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
            {
                dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
            };


        }


        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.DataSource = service.SearchRevenueMachineAccountInvoiceByCondition((RevenueMachineAccountInvoiceSearchCriteria)e.Condition, gridOrderList.SortExpression,
                                                      gridOrderList.SortDirection, e.PageSize, e.PageIndex);

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.RecordCount = service.GetRevenueMachineAccountInvoicesCount((RevenueMachineAccountInvoiceSearchCriteria)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new RevenueMachineAccountInvoiceSearchCriteria
            {
               
            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }
      

            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }
            DateTime? dateStart = null, dateEnd = null;
  
            if (!string.IsNullOrEmpty(txtConfirmInvoiceDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtConfirmInvoiceDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtConfirmInvoiceDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtConfirmInvoiceDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ConfirmInvoiceDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (!string.IsNullOrEmpty(txtInvoiceNo.Text))
            {
                criteria.InvoiceNO = txtInvoiceNo.Text.Trim();
            }

            e.Condition = criteria;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));


                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit1");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyOrder('{0}');return false;", orderId);
                }

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteOrderInvoice('{0}');return false;", orderId);
                }

            }
        }
        protected void gridProductList_RowDetailCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderId = gridOrderList.DataKeys[e.Row.RowIndex]["Id"].ToString().ToGuid();
                var service = ServiceContainer.GetService<IRevenueMachineAccountService>();

                grdInvoiceOrder.DataSource = service.GetRevenueMachineAccountInvoiceOrders(issuingOrderId);
                grdInvoiceOrder.DataBind();

            }
        }


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var orderId = fieldOrderId.Value.ToGuid();
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            //check status
            if (!IsManager())
            {
                if (service.GetRevenueMachineAccountInvoice(orderId).TotalAccountReceiptAmount > 0)
                {
                    Alert("该笔发票已经有收款记录，不可以删除!");
                    return;

                }
            }
            if (service.RemoveRevenueMachineAccountInvoices(orderId))
            {
                PageQueryAdapter1.ReloadCurrentPage();
                Alert("删除成功!");
            }
        }

        protected void grdInvoiceOrder_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
  
            }
        }

        protected decimal GetProfitRate(object profit, object totalRevenues)
        {
            if (MiscUtilities.IsNullOrEmpty(totalRevenues)) return 0;
            if (MiscUtilities.IsNullOrEmpty(profit)) return 0;
            if (totalRevenues.ToString().ToDecimal() == 0) return 0;
            return Math.Round(((profit.ToString().ToDecimal() / totalRevenues.ToString().ToDecimal() ?? 0) * 100), 2);

        }


        protected string GetDeliveryAddress(object issuingId)
        {
            if (MiscUtilities.IsNullOrEmpty(issuingId)) return string.Empty;
            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderDeliveryData = orderService.GetIssuingOrderDeliveryByOrderId(issuingId.ToString().ToGuid());

            return issuingOrderDeliveryData.Select(a => a.DeliveryAddress).Aggregate((a, b) => a + "," + b);

        }

        protected string GetShortDeliveryAddress(object issuingId)
        {
            var deliveryAddress = GetDeliveryAddress(issuingId);
            if (string.IsNullOrWhiteSpace(deliveryAddress) || deliveryAddress.Length <= 10)
                return deliveryAddress;
            return deliveryAddress.Substring(0, 10) + "...";

        }
    }
}